import ast
import os
import sys
from typing import Dict, List, Tuple, Optional
from pathlib import Path

from .cfg_builder import CFGBuilder
from .path_generator import BasicPathGenerator
from .utils import TempFileManager


def analyze_function(file_path: str, function_name: str):
    """
    分析指定函数，生成CFG和基本路径集

    :param file_path: 源文件路径
    :param function_name: 函数名
    :return: 包含基本路径集、节点信息和边信息的元组，或None(分析失败时)
    """

    try:
        # 读取源代码
        with open(file_path, 'r', encoding='utf-8') as f:
            source_code = f.read()

        # 解析AST
        tree = ast.parse(source_code)

        # 查找目标函数定义
        for node in tree.body:
            if isinstance(node, ast.FunctionDef) and node.name == function_name:
                # 获取函数源代码
                func_source = ast.get_source_segment(source_code, node)

                print(f"\n开始分析函数 '{function_name}' 的控制流...")

                # 构建CFG
                cfg_builder = CFGBuilder()
                adj_matrix, nodes, edges = cfg_builder.build_cfg(func_source)

                # 保存CFG图像
                cfg_filename = f"./images/{function_name}_cfg"
                try:
                    cfg_builder.save_cfg_as_png(cfg_filename)
                    print(f"CFG已保存为 {os.path.abspath(cfg_filename)}.png")
                except Exception as e:
                    print(f"警告：无法保存CFG图像: {e}")

                print("\nCFG邻接矩阵：")
                for row in adj_matrix:
                    print(row)

                print(f"\n开始生成函数 {function_name} 的基本路径集...")

                # 生成基本路径
                path_gen = BasicPathGenerator(adj_matrix)
                paths = path_gen.find_all_paths(start=2, end=len(adj_matrix) - 1, max_depth=30)

                if not paths:
                    print("⚠️ 未找到任何路径！请检查CFG是否连通")
                else:
                    print(f"\n发现 {len(paths)} 条基本路径:")
                    for i, path in enumerate(paths):
                        path = [node - 1 for node in path]
                        print(f"P{i + 1}: {path}")

                return paths, nodes, edges

        print(f"❌ 未找到名为 {function_name} 的函数定义")
        return None

    except FileNotFoundError:
        print(f"❌ 文件 {file_path} 未找到")
        return None
    except UnicodeDecodeError:
        print(f"❌ 无法解码文件 {file_path}，请确保文件编码正确")
        return None
    except Exception as e:
        print(f"❌ 分析错误: {str(e)}")
        return None
